package com.qf.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.qf.mapper.DtsGoodsMapper;
import com.qf.pojo.*;
import com.qf.service.*;
import com.qf.util.AdminResponseCode;
import com.qf.util.AdminResponseUtil;
import com.qf.util.ResponseUtil;
import com.qf.vo.GoodsAllinone;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author 千峰教育
 * @Company http://www.mobiletrain.org/
 * @Version 1.0
 */
@Service
public class DtsGoodsServiceImpl implements DtsGoodsService {

    @Autowired
    DtsGoodsMapper goodsMapper;

    @Autowired
    DtsCategoryService categoryService;

    @Autowired
    DtsGoodsAttributeService attributeService;

    @Autowired
    DtsGoodsSpecificationService specificationService;

    @Autowired
    DtsGoodsProductService productService;

    @Autowired
    DtsBrandService brandService;

    @Autowired
    DtsGoodsOrderService goodsOrderService;
    @Autowired
    DtsCartService cartService;

    @Override
    public Integer findTotal() {
        LambdaQueryWrapper<DtsGoods> wrapper
                = new LambdaQueryWrapper<>();

        wrapper.eq(DtsGoods::getDeleted ,false);

        Integer count = goodsMapper.selectCount(wrapper);

        return count;
    }

    @Override
    public IPage<DtsGoods> findPage(Integer page, Integer limit, String sort,
                                    String order, String name, String goodSn, List<Integer> brandIds) {

        IPage<DtsGoods> ipage = new Page<>(page, limit);

        QueryWrapper<DtsGoods> wrapper = new QueryWrapper<>();

        if(!StringUtils.isEmpty(name)){
            wrapper.like("name", name);
        }

        if(!StringUtils.isEmpty(goodSn)){
            wrapper.eq("goodSn", goodSn);
        }

        if(brandIds != null && brandIds.size() > 0 ){
            wrapper.in("brand_id", brandIds);
        }

        if(order.equalsIgnoreCase("asc")){
            wrapper.orderByAsc(sort);
        }else{
            wrapper.orderByDesc(sort);
        }

        ipage = goodsMapper.selectPage(ipage,wrapper );

        return ipage;
    }

    @Override
    public Map<String, Object> findById(Integer id) {
        //1， 先查询商品信息
        DtsGoods goods = goodsMapper.selectById(id);

        //2. 查询上的 分类id（一级分类和二级分页id）
        List<Integer> categoryIds = categoryService.findCategoryId(goods.getCategoryId());

        //3. 商品的属性
        List<DtsGoodsAttribute> attributes = attributeService.findGoodsAttribute(id);

        //4. 商品的规格
        List<DtsGoodsSpecification> specifications = specificationService.findGoodsSpecification(id);
        //5. 商品的库存
        List<DtsGoodsProduct> products = productService.findGoodsProduct(id);


        Map<String,Object> data = new HashMap<>();
        data.put("categoryIds", categoryIds);
        data.put("goods", goods);
        data.put("attributes", attributes);
        data.put("specifications", specifications);
        data.put("products", products);
        return data;
    }

    @Override
    public Object update(GoodsAllinone goodsAllinone) {
        Object error = validate(goodsAllinone);
        //如果返回了错误消息
        if(error != null){
            return error;
        }

        DtsGoods goods = goodsAllinone.getGoods();
        DtsGoodsAttribute[] attributes = goodsAllinone.getAttributes();
        DtsGoodsProduct[] products = goodsAllinone.getProducts();
        DtsGoodsSpecification[] specifications = goodsAllinone.getSpecifications();

        //在修改前，判断是否在 购物车或者订单表存在, 如果已存在，则不能修改
        int orderCnt = goodsOrderService.findCountByGid(goods.getId());
        int cartCnt = cartService.findCountByGid(goods.getId());
        if(orderCnt > 0 || cartCnt > 0){
            return AdminResponseUtil.fail(AdminResponseCode.GOODS_UPDATE_NOT_ALLOWED);
        }

        //更新数据库
        //更新 商品基本信息
        goodsMapper.updateById(goods);

        //删除商品的属性
        attributeService.deleteByGid(goods.getId());

        //新增商品的属性
        for (DtsGoodsAttribute attribute : attributes) {
            attribute.setGoodsId(goods.getId());
            attributeService.insert(attribute);
        }

        //删除商品规格
        specificationService.deleteByGid(goods.getId());

        //新增商品的规格
        for (DtsGoodsSpecification specification : specifications) {
            specification.setGoodsId(goods.getId());
            specificationService.insert(specification);
        }

        //删除商品的库存
        productService.deleteByGid(goods.getId());

        //新增商品的库存
        for (DtsGoodsProduct product : products) {
            product.setGoodsId(goods.getId());
            productService.insert(product);
        }


        return ResponseUtil.ok();


    }

    @Override
    public void delete(Integer id) {

        //删除属性
        attributeService.deleteByGid(id);
        //删除库存
        productService.deleteByGid(id);
        //删除规格
        specificationService.deleteByGid(id);
        //删除商品
        goodsMapper.deleteById(id);
    }

    @Override
    public Object add(GoodsAllinone one) {

        Object error = this.validate(one);
        if(error != null){
            return error;
        }

        DtsGoods goods = one.getGoods();
        DtsGoodsAttribute[] attributes = one.getAttributes();
        DtsGoodsProduct[] products = one.getProducts();
        DtsGoodsSpecification[] specifications = one.getSpecifications();

        //判断商品名称是否存在
        LambdaQueryWrapper<DtsGoods> wrapper = new LambdaQueryWrapper<>();

        wrapper.eq(DtsGoods::getName , goods.getName());

        Integer count = goodsMapper.selectCount(wrapper);
        if(count > 0){
            return AdminResponseUtil.fail(AdminResponseCode.GOODS_NAME_EXIST);
        }

        //新增商品
        goods.setAddTime(new Date());
        goods.setUpdateTime(new Date());
        goods.setDeleted(false);
        //在商品添加完成后， mybatis-plus会自动帮助我们获取 主键
        goodsMapper.insert(goods);


        //新增商品属性
        for (DtsGoodsAttribute attribute : attributes) {
            attribute.setGoodsId(goods.getId());
            attributeService.insert(attribute);
        }
        //新增商品库存
        for (DtsGoodsProduct product : products) {
            product.setGoodsId(goods.getId());
            productService.insert(product);
        }
        //新增商品规格
        for (DtsGoodsSpecification specification : specifications) {
            specification.setGoodsId(goods.getId());
            specificationService.insert(specification);
        }

        return ResponseUtil.ok();
    }

    private Object validate(GoodsAllinone goodsAllinone) {
        //获取商品基本信息
        DtsGoods goods = goodsAllinone.getGoods();
        if(goods == null){
            return ResponseUtil.badArgument();
        }

        if(StringUtils.isEmpty(goods.getName()) || StringUtils.isEmpty(goods.getGoodsSn())){
            return AdminResponseUtil.fail(-1, "商品名称或者编号不能为null");
        }
        //获取品牌id
        Integer brandId = goods.getBrandId();

        if(brandId != null){
            boolean flag = brandService.isExists(brandId);
            if(! flag ){
                return ResponseUtil.fail(-1,  "品牌商不存在");
            }
        }
        //获取（二级）分类id
        Integer categoryId = goods.getCategoryId();
        if(categoryId != null){
            boolean flag = categoryService.isExists(categoryId);
            if(! flag ){
                return ResponseUtil.fail(-1,  "商品分类不存在");
            }
        }

        //获取商品的属性
        DtsGoodsAttribute[] attributes = goodsAllinone.getAttributes();
        if(attributes == null || attributes.length == 0){
            return ResponseUtil.fail(-1, "商品属性必须设置");
        }
        //获取商品的库存
        DtsGoodsProduct[] products = goodsAllinone.getProducts();
        if(products == null || products.length == 0){
            return ResponseUtil.fail(-1, "商品库存必须设置");
        }
        //获取商品的规格
        DtsGoodsSpecification[] specifications = goodsAllinone.getSpecifications();
        if(specifications == null || specifications.length == 0){
            return ResponseUtil.fail(-1, "商品规格必须设置");
        }


        return null;
    }
}
